#include "fasta_parser.h"

namespace fasta_parser
{

using std::ifstream;
using std::pair;
using std::string;
using std::map;
using std::cerr;
using std::endl;

FastaParser::FastaParser(char const* filename)
{
  fasta.open(filename);
}

FastaParser::~FastaParser()
{
  fasta.close();
}

// sequence (out) - next pair (header, content) in fasta stream (in lower case)
void FastaParser::GetNextSequenceFasta(pair<string, string>* sequence)
{
  string line;
  getline(fasta, line);
  if (line[0] == '>')
  {
    sequence->first = line;
    getline(fasta, line);
  }
  else
  {
    cerr << "Unexpected character" << endl;
    throw "Unexpected character";
  }

  while (line[0] != '>' && fasta)
  {
    sequence->second += line;
    char beginning = fasta.peek();
    if (beginning == '>')
    {
      break;
    }
    else
    {
      getline(fasta, line);
    }
  }

  transform(sequence->first.begin(), sequence->first.end(), 
            sequence->first.begin(), ::tolower);
  transform(sequence->second.begin(), sequence->second.end(), 
            sequence->second.begin(), ::tolower);
}

// result (out) - map (header, content) of all fasta records in file (in lower 
// case)
void FastaParser::GetAllFastaSequencesPairs(map<string, string>* result)
{
  result->clear();

  while (fasta)
  {
    pair<string, string> next_sequence;
    GetNextSequenceFasta(&next_sequence);
    (*result)[next_sequence.first] = next_sequence.second;
  }
}

} //namespace fasta_parser